package com.rico.smart.socket;

import com.rico.smart.message.IMessage;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketClient{

    private int port;

    private String host;

    private Socket socket;

    private SocketConnection socketConnection;

    private IMessage iMessage;

    public SocketClient(String host, int port){
        this.port=port;
        this.host=host;

    }

    public boolean connect() throws IOException {
        if(socket!=null){
            try {
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port));
        socketConnection =new SocketConnection(socket);
        return true;
    }

    public void sendMessage(IMessage iMessage) throws IOException {
        socketConnection.sendMessage(iMessage);
    }

    public IMessage sendMessageAndWaitResponse(IMessage iMessage,int waitTime) throws IOException {
       return socketConnection.sendMessageAndWaitRespone(iMessage,waitTime);
    }

    public SocketConnection getSocketConnection() {
        return socketConnection;
    }

    public void setSocketConnection(SocketConnection socketConnection) {
        this.socketConnection = socketConnection;
    }

    public void close(){
        try {
            socketConnection.setConnected(false);
            if(socket!=null) {
                this.socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public boolean isConnected(){
        if(socketConnection==null){
            return false;
        }
        return this.socketConnection.isConnected();
    }

    public void setMessageHandler(MessageHandler messageHandler) {
        socketConnection.setMessageHandler(messageHandler);
    }
}
